﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using VIT.Web.UI;
using Wedding.Provider;
using VIT.Library.Images;

namespace VIT.Wedding.Admin
{
    public partial class StypeList : VITComponent
    {
        private WeddingContext WeddingContext
        {
            get { return (HttpContext.Current.ApplicationInstance as Global).WeddingContext; }
        }

        private void SearchData()
        {
            lsvTypeWedding.InsertItemPosition = InsertItemPosition.None;
            lsvTypeWedding.EditIndex = -1;
            lsvTypeWedding.DataBind();
        }

        private void LoadLanguage()
        {
            ddlLang.DataSource = WeddingContext.GetQuery<Language>();
            ddlLang.DataTextField = "Name";
            ddlLang.DataValueField = "Id";
            ddlLang.DataBind();

            ddlLang.SelectedValue = Session["language"].ToString();
        }

        private void deleteList(string[] listId)
        {
            List<string> pathImages = new List<string>();
            WeddingContext.OpenTransaction();
            foreach (string id in listId)
            {
                var item = WeddingContext.GetObject<Product_Style>(c => c.Id == int.Parse(id));
                if (item != null)
                {
                    pathImages.Add(item.ImagePath);
                }
                WeddingContext.DeleteObject<Product_Style>(c => c.Id == int.Parse(id));
            }
            if (WeddingContext.CommitTransaction())
            {
                foreach (var item in pathImages)
                {
                    if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/TypeWedding/Details/" + item))
                        System.IO.File.Delete(URLBaseDir + "Uploads/Images/TypeWedding/Details/" + item);
                    if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/TypeWedding/Thumbs/" + item))
                        System.IO.File.Delete(URLBaseDir + "Uploads/Images/TypeWedding/Thumbs/" + item);
                }
            }
            lsvTypeWedding.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            lsvTypeWedding.DelegateDataSource = new Controls.WSEnumerableDelegate(delegate(int skip, int take, ref int count)
                {
                    var result = WeddingContext.GetQuery<Product_Style>().Skip(skip);
                    if (take >= 0) result.Take(take);
                    count = result.Count();
                    return result.ToArray();
                });
            if (!IsPostBack)
            {
                Session["order"] = "Orders";
                LoadLanguage();
                SearchData();
            }
        }

        protected void lsvTypeWedding_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            lsvTypeWedding.InsertItemPosition = InsertItemPosition.None;
            lsvTypeWedding.EditIndex = e.NewEditIndex;
            lsvTypeWedding.DataBind();
        }

        protected void lsvTypeWedding_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            lsvTypeWedding.InsertItemPosition = InsertItemPosition.None;
            lsvTypeWedding.EditIndex = -1;
            var txtName = e.Item.FindControl("txtName") as TextBox;
            var txtDescription = e.Item.FindControl("txtDescription") as TextBox;
            var fupType = e.Item.FindControl("fupType") as FileUpload;
            var objType = new Product_Style();
            objType.Name = txtName.Text.Trim();
            objType.Description = txtDescription.Text.Trim();
            if (fupType.HasFile)
            {
                objType.ImagePath = String.Format("{0:yyMMddhhmmss}", DateTime.Now) + System.IO.Path.GetExtension(fupType.FileName);
                try
                {
                    // save
                    fupType.SaveAs(URLBaseDir + "Uploads/Images/TypeWedding/Details/" + objType.ImagePath);
                    new ResizeImage().Resize(URLBaseDir + "/Uploads/Images/TypeWedding/Details/" + objType.ImagePath, URLBaseDir + "/Uploads/Images/TypeWedding/Thumbs/" + objType.ImagePath, 150);
                }
                catch (Exception ex) { throw ex; }
            }
            WeddingContext.AddObject(objType);
            lsvTypeWedding.DataBind();
        }

        protected void lsvTypeWedding_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            lsvTypeWedding.InsertItemPosition = InsertItemPosition.None;
            lsvTypeWedding.EditIndex = -1;
            var item = lsvTypeWedding.Items[e.ItemIndex];
            var txtName = item.FindControl("txtName") as TextBox;
            var txtDescription = item.FindControl("txtDescription") as TextBox;
            var fupType = item.FindControl("fupType") as FileUpload;

            var objType = WeddingContext.GetObject<Product_Style>(c => c.Id == Convert.ToInt32(e.Keys[0]));
            if (objType != null)
            {
                objType.Name = txtName.Text.Trim();
                objType.Description = txtDescription.Text.Trim();
                if (fupType.HasFile)
                {
                    try
                    {
                        // delete
                        if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/TypeWedding/Details/" + objType.ImagePath))
                            System.IO.File.Delete(URLBaseDir + "Uploads/Images/TypeWedding/Details/" + objType.ImagePath);
                        if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/TypeWedding/Thumbs/" + objType.ImagePath))
                            System.IO.File.Delete(URLBaseDir + "Uploads/Images/TypeWedding/Thumbs/" + objType.ImagePath);
                        
                        // save
                        objType.ImagePath = String.Format("{0:yyMMddhhmmss}", DateTime.Now) + System.IO.Path.GetExtension(fupType.FileName);
                        fupType.SaveAs(URLBaseDir + "Uploads/Images/TypeWedding/Details/" + objType.ImagePath);
                        new ResizeImage().Resize(URLBaseDir + "/Uploads/Images/TypeWedding/Details/" + objType.ImagePath, URLBaseDir + "/Uploads/Images/TypeWedding/Thumbs/" + objType.ImagePath, 150);
                    }
                    catch (Exception ex) { throw ex; }
                }
                WeddingContext.UpdateObject(c => c.Id == objType.Id, objType);
            }
            lsvTypeWedding.DataBind();
        }

        protected void lsvTypeWedding_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            lsvTypeWedding.InsertItemPosition = InsertItemPosition.None;
            lsvTypeWedding.EditIndex = -1;
            lsvTypeWedding.DataBind();
        }

        protected void ddlLang_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["language"] = ddlLang.SelectedValue;
        }

        protected void Insert_Click(object sender, EventArgs e)
        {
            lsvTypeWedding.EditIndex = -1;
            lsvTypeWedding.InsertItemPosition = InsertItemPosition.FirstItem;
            lsvTypeWedding.DataBind();
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            string[] check = Request["itemCheckbox"].Split(',');
            deleteList(check);
        }

        protected void sortedChange_OnClick(object sender, EventArgs e)
        {
        }
    }
}